package com.itheima.stargraph.service;

import com.itheima.stargraph.pojo.ComfyuiModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@Component
public class FreemarkerService {
    @Autowired
    private Configuration configuration;

    public String renderWorkflow(ComfyuiModel comfyuiModel){
        //获取模板对象
        try {
            Template template = configuration.getTemplate("workflow.ftl");
            //准备数据
            Map<String,ComfyuiModel> map = new HashMap<>();
            map.put("config", comfyuiModel);
            //创建输出流
            StringWriter out = new StringWriter();
            //执行渲染
            template.process(map, out);
            //返回JSON字符串
            String result = new String(out.toString().getBytes(StandardCharsets.UTF_8));
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return null;
    }
}
